package ar.edu.itba.tp1.tpmariano;

import ar.edu.itba.tp1.gps.api.GPSState;

public class Heuristic1Problem extends Problem {
		
	protected GPSState solutionState;
	
	public Heuristic1Problem(){
		super();
		this.solutionState = buildSolutionState();
	}
	
	private GPSState buildSolutionState() {
		Grid solution = new Grid();
		
		solution.putTile(0, 0, 1, 2, 0, 0);
		solution.putTile(1, 0, 4, 1, 0, 2);
		solution.putTile(2, 0, 3, 2, 0, 1);
		solution.putTile(3, 0, 1, 0, 0, 2);
		solution.putTile(0, 1, 1, 4, 1, 0);
		solution.putTile(1, 1, 3, 3, 4, 4);
		solution.putTile(2, 1, 4, 4, 3, 3);
		solution.putTile(3, 1, 2, 0, 1, 4);
		solution.putTile(0, 2, 1, 3, 1, 0);
		solution.putTile(1, 2, 3, 4, 3, 3);		
		solution.putTile(2, 2, 4, 3, 4, 4);
		solution.putTile(3, 2, 2, 0, 2, 3);
		solution.putTile(0, 3, 0, 1, 1, 0);
		solution.putTile(1, 3, 0, 2, 3, 1);
		solution.putTile(2, 3, 0, 2, 4, 2);
		solution.putTile(3, 3, 0, 0, 2, 2);
		
		return solution;
	}
	
	@Override
	public Integer getHValue(GPSState state) {
		Grid currentGrid = (Grid)state;
		Grid solutionGrid = (Grid)solutionState;
		int HValue = 16;
		
		for(int x = 0; x < LENGTH; x++)
			for(int y = 0; y < LENGTH; y++)
				if(checkTiles(currentGrid.getTile(x, y), solutionGrid.getTile(x, y)))
					HValue--;
		
		return HValue;
	}
	
	protected boolean checkTiles(char currentTile, char solutionTile){
		for(int i = 0; i < 4; i++) {
			if(currentTile == solutionTile)
				return true;
			else
				// Rotate right
				currentTile = (char)(((currentTile >> 4) & 4095) | ((currentTile & 0xF) << 12));
		}
		return false;
	}

}
